<?php

namespace common\models;

use common\helpers\commonApi;
use EasyWeChat\Factory;
use Yii;

/**
 * This is the model class for table "{{%order_refund}}".
 *
 * @property int $id
 * @property string|null $sn 退款单号
 * @property int|null $userid 用户id
 * @property int|null $order_id 订单id
 * @property int|null $order_good_id 订单商品id
 * @property float|null $amount 退款金额
 * @property string|null $refund_way 处理方式
 * @property string|null $cause 原因
 * @property string|null $imgs 图片
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 * @property int|null $status 状态
 * @property string|null $review_time 审核时间
 * @property string|null $review_remark 审核备注
 * @property string|null $info 信息
 */
class OrderRefund extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%order_refund}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'order_id', 'order_good_id', 'status'], 'integer'],
            [['amount'], 'number'],
            [['cause', 'imgs', 'review_remark', 'info'], 'string'],
            [['create_time', 'update_time', 'review_time'], 'safe'],
            [['sn', 'refund_way'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sn' => '退款单号',
            'userid' => '用户id',
            'order_id' => '订单id',
            'order_good_id' => '订单商品id',
            'amount' => '退款金额',
            'refund_way' => '处理方式',
            'cause' => '原因',
            'imgs' => '图片',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'status' => '状态',
            'review_time' => '审核时间',
            'review_remark' => '审核备注',
            'info' => '信息',
        ];
    }

    /**
     * 创建订单号
     * @return mixed|string
     */
    public static function makeOrderid()
    {
        $orderId = time() . '' . rand(1000, 9999);
        if (self::find()->where(['sn' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }

    /**
     * 退款
     * @param $order_id 订单id
     * @param $refundNumber 退款订单号
     * @param $refundFee 退款金额
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function refund($order_id,$refundNumber,$refundFee)
    {
        $order = Order::find()
            ->where(['id'=>$order_id,'pay_status'=>[1,3]])
            ->select(['refund_status','pay_amount','id','party_order','pay_status'])
            ->one();
        if (!$order){
            return commonApi::message('该订单不能进行退款',false);
        }
        $system = System::getModel();
        if (!$system->a_appid||!$system->a_secret){
            return commonApi::message('请设置小程序appid和secret',false);
        }
        $config = [
            'app_id'             => $system->a_appid,
            'mch_id'             => $system->mch_id,
            'key'                => $system->pay_key,   // API 密钥
            'cert_path'          => dirname(Yii::$app->BasePath).$system->cert_path, // XXX: 绝对路径！！！！
            'key_path'           => dirname(Yii::$app->BasePath).$system->key_path,      // XXX: 绝对路径！！！！
        ];
        $payment = Factory::payment($config);
        $result = $payment->refund->byOutTradeNumber($order->party_order, $refundNumber, $order->pay_amount*100, $refundFee*100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退款',
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['return_msg'] == 'OK'){
            if (empty($result['err_code_des'])) {
                $old_amount = self::find()->where(['order_id'=>$order_id,'status'=>1])->sum('amount');
                $old_amount = $old_amount??0;
                $old_amount = $old_amount+$refundFee;
                if ($order->pay_amount-$old_amount==0){
                    $order->refund_status = 2;
                }else{
                    $order->refund_status = 1;
                }
                $order->pay_status = 2;
                $order->save();
                return commonApi::message('退款成功',true,$result);
            }
        }
        return commonApi::message('退款失败：'.$result['err_code_des'],false);
    }
}
